from django.shortcuts import render,redirect
from django.http import HttpResponseNotFound,HttpResponse

from rest_framework.decorators import api_view
from rest_framework.response import Response


import os
from django.conf import settings
# Create your views here.

# 登入
def login(request):
    if request.method == "GET":
        return render(request,"login.html")

    elif request.method == "POST":
        acc = request.POST.get("acc",None)
        pd = request.POST.get("pd",None)
        response = redirect("/index/")
        # 浏览器关闭就过期
        response.set_cookie("login_state","1",max_age=None)
        if acc == "long" and pd == "secret":
            return response
        return redirect("/login/")

    return HttpResponseNotFound("你的请求方式有误")

# 进入首页
def index(request):
    login_state = request.COOKIES.get("login_state",None)
    if not login_state:
        return redirect("/login/")
    return render(request,'index.html')

# 批量增加图片
@api_view(["POST"])
def add_picture(request):
    try:
        files = request.FILES.getlist("pictures")
        print(len(files))
        def save_single_file(filename):
            filepath = os.path.join(settings.BASE_DIR,"ablum","static",filename)
            # 同名的照片直接跳过上传
            if not os.path.exists(filepath):
                with open(filepath,"wb+") as f:
                    for c in file.chunks():
                        f.write(c)
        count = 1
        for file in files:
            save_single_file(file.name)
            count += 1
        return Response({"state":"success"})
    except:
        # 上传失败
        return Response({"state":"failure"})


# 获取分页数据
from django.core.paginator import Paginator

@api_view(["get"])
def get_n_page(request):
    pageNum = request.GET.get("pageNum",1)
    # 拿到所有的照片文件
    pictures = os.listdir(os.path.join(settings.BASE_DIR,"ablum","static"))
    # 过滤一些非照片文件，比如css
    def filter_non_pic(name:str):
        if name.endswith(".jpg") or name.endswith(".png"):
            return True
        return False
    pictures = list(filter(filter_non_pic,pictures))
    page = Paginator(pictures,10)
    data = page.page(pageNum).object_list
    totalPageNum = page.num_pages
    return Response({"data":data,"totalPageNum":totalPageNum})
